package com.supermap.localization.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.oro.text.regex.MalformedPatternException;

import com.supermap.localization.api.LineReplacer;
import com.supermap.localization.commontypes.SampleInfo;

public class LineReplacerImpl implements LineReplacer {

    @Override
    public String replace(String str, Map<String, SampleInfo> sampleInfos) throws MalformedPatternException {
        List<String> matcherResult = ExtractManager.extract(str);
        matcherResult = sortByLengthDesc(matcherResult);
        for (int i = 0; i < matcherResult.size(); i++) {
            String replaceStr = matcherResult.get(i);
            if (sampleInfos.containsKey(replaceStr)) {
                str = StringUtils.replace(str, sampleInfos.get(replaceStr).getKey(), sampleInfos.get(replaceStr).getValue());
            }
        }
        return str;
    }

    private List<String> sortByLengthDesc(List<String> strlist) {
        Collections.sort(strlist, new Comparator<String>() {

            public int compare(String arg0, String arg1) {
                return arg1.length() - arg0.length();
            }

        });
        return strlist;
    }

}
